package org.light.simpleauth;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.exception.ValidateException;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class AuthUtilRsMethodGenerator {
	public static Method generatePureGenerateSaltMethod(){
		Method method = new Method();
		method.setStandardName("pure_generate_salt");
		method.setReturnType(new Type("Result<String, Error>"));
	
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,1,"let mut salt = \"\".to_string();"));
		sList.add(new Statement(2000L,1,"let saltletters = vec!['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];"));
		sList.add(new Statement(3000L,1,"let mut rng = rand::thread_rng();"));
		sList.add(new Statement(4000L,0,""));
		sList.add(new Statement(5000L,1,"for i in 0..8 {"));
		sList.add(new Statement(6000L,2,"let rand_num: usize = rng.gen_range(0..16);"));
		sList.add(new Statement(7000L,2,"salt.push(*saltletters.get(rand_num).unwrap());"));
		sList.add(new Statement(8000L,1,"}"));
		sList.add(new Statement(9000L,1,"Ok(salt)"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	
	public static Method generateGenerateSaltMethod(Domain domain){
		Method method = new Method();
		method.setStandardName("generate_salt");
		method.setReturnType(new Type("Result<String, Error>"));
	
		List<Writeable> sList = new ArrayList<Writeable>();
		
		sList.add(new Statement(1000L,1,"let mut salt = pure_generate_salt().await.unwrap();"));
		sList.add(new Statement(2000L,1,"while unique_salt(salt.clone()).await.unwrap() == false {"));
		sList.add(new Statement(3000L,2,"salt = pure_generate_salt().await.unwrap();"));
		sList.add(new Statement(4000L,1,"}"));
		sList.add(new Statement(5000L,1,"Ok(salt.clone())"));

		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	
	public static Method generateUniqueSaltMethod(Domain domain) throws ValidateException {
		Method method = new Method();
		method.setStandardName("unique_salt");
		method.addSignature(new Signature(1, "salt","String"));
		method.setReturnType(new Type("Result<String, Error>"));
	
		List<Writeable> sList = new ArrayList<Writeable>();
		
		sList.add(new Statement(1000L,1,"let app_state = init_db();"));
		sList.add(new Statement(2000L,1,"let count = app_state.await.context."+StringUtil.getSnakeName(domain.getPlural())+".count_salt(salt).await.unwrap().count_num;"));
		sList.add(new Statement(3000L,1,"Ok(count==0)"));

		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
}
